#include "xcb-region.h"
#include <xcb/xcb.h>
#include <xcb/xfixes.h>
#include <qpa/qplatformnativeinterface.h>
#include <QQuickView>
#include <QQuickItem>
#include <QGuiApplication>
static inline xcb_rectangle_t qRectToXCBRectangle(const QRect &r)
{
    xcb_rectangle_t result;
    result.x = qMax(SHRT_MIN, r.x());
    result.y = qMax(SHRT_MIN, r.y());
    result.width = qMin((int)USHRT_MAX, r.width());
    result.height = qMin((int)USHRT_MAX, r.height());
    return result;
}

void  XCB_Region::updateInputRegion () {

    static QQuickItem *root = nullptr;
    if(!root) root = qobject_cast<QQuickItem*>(view->rootObject());
    QVector<xcb_rectangle_t> rects;
    //rects.push_back(qRectToXCBRectangle(d->keyboardRect.toRect()));
    rects.push_back(qRectToXCBRectangle(qvariant_cast<QRect>(root->property("keyboardRect"))));
    //if (d->previewVisible && !d->previewRect.isEmpty())
    //    rects.push_back(qRectToXCBRectangle(d->previewRect.toRect()));

    //QWindow *window = d->view.data();
    QWindow *window = qobject_cast<QWindow*>(view);
    QPlatformNativeInterface *platformNativeInterface = QGuiApplication::platformNativeInterface();
    xcb_connection_t *xbcConnection = static_cast<xcb_connection_t *>(
                platformNativeInterface->nativeResourceForWindow(
                    "connection", window));
    xcb_xfixes_region_t xbcRegion = xcb_generate_id(xbcConnection);
    xcb_xfixes_create_region(xbcConnection, xbcRegion, rects.size(), rects.constData());
    xcb_xfixes_set_window_shape_region(xbcConnection, window->winId(), XCB_SHAPE_SK_INPUT, 0, 0, xbcRegion);
    xcb_xfixes_destroy_region(xbcConnection, xbcRegion);
}

